<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-blue-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <!-- Icon placeholder -->
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="lucide lucide-calculator w-8 h-8 text-white"
          >
            <rect width="16" height="20" x="4" y="2" rx="2" ry="2" />
            <path d="M8 6h8" />
            <path d="M8 10h8" />
            <path d="M8 14h8" />
            <path d="M8 18h8" />
          </svg>
        </div>
        <CardTitle class="text-2xl text-slate-800">{{
          t("mathTest.title")
        }}</CardTitle>
        <p class="text-slate-600 mt-2">{{ t("mathTest.description") }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div
          class="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl p-6 border border-blue-100"
        >
          <h3 class="font-semibold text-blue-900 mb-4 flex items-center gap-2">
            <!-- Icon placeholder -->
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="lucide lucide-star w-5 h-5"
            >
              <polygon
                points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"
              />
            </svg>
            {{ t("mathTest.instructions.title") }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >1</span
              >
              <p>{{ t("mathTest.instructions.item1") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >2</span
              >
              <p>{{ t("mathTest.instructions.item2") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >3</span
              >
              <p>{{ t("mathTest.instructions.item3") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >4</span
              >
              <p>{{ t("mathTest.instructions.item4") }}</p>
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div
            class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200"
          >
            <h4 class="font-semibold text-green-800 mb-2">
              {{ t("mathTest.categories.arithmetic") }}
            </h4>
            <p class="text-sm text-green-700">
              {{ t("mathTest.categories.arithmeticDescription") }}
            </p>
          </div>
          <div
            class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200"
          >
            <h4 class="font-semibold text-purple-800 mb-2">
              {{ t("mathTest.categories.algebraGeometry") }}
            </h4>
            <p class="text-sm text-purple-700">
              {{ t("mathTest.categories.algebraGeometryDescription") }}
            </p>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200"
          >
            <div class="text-2xl font-bold text-blue-600 mb-1">
              {{ t("mathTest.stats.dynamic") }}
            </div>
            <div class="text-sm text-blue-700">
              {{ t("mathTest.stats.questionGeneration") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200"
          >
            <div class="text-2xl font-bold text-cyan-600 mb-1">20</div>
            <div class="text-sm text-cyan-700">
              {{ t("mathTest.stats.questionCountLabel") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-blue-50 to-cyan-50 rounded-xl border border-blue-200"
          >
            <div class="text-2xl font-bold text-slate-600 mb-1">10</div>
            <div class="text-sm text-slate-700">
              {{ t("mathTest.stats.timeLimitLabel") }}
            </div>
          </div>
        </div>

        <Button
          @click="handleStartTest"
          class="w-full bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
        >
          {{ t("mathTest.startButton") }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div
    v-else-if="stage === 'test' && questions.length > 0"
    class="max-w-4xl mx-auto space-y-6"
  >
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge
          variant="outline"
          class="bg-blue-100 text-blue-700 border-blue-300"
        >
          {{ t("mathTest.questionNumberPrefix") }} {{ currentQuestion + 1 }} /
          {{ questions.length }}
        </Badge>
        <Badge
          variant="outline"
          :class="`${
            questions[currentQuestion].type === 'arithmetic'
              ? 'bg-green-100 text-green-700 border-green-300'
              : questions[currentQuestion].type === 'algebra'
              ? 'bg-purple-100 text-purple-700 border-purple-300'
              : questions[currentQuestion].type === 'geometry'
              ? 'bg-orange-100 text-orange-700 border-orange-300'
              : questions[currentQuestion].type === 'percentage'
              ? 'bg-yellow-100 text-yellow-700 border-yellow-300'
              : questions[currentQuestion].type === 'fraction'
              ? 'bg-pink-100 text-pink-700 border-pink-300'
              : 'bg-indigo-100 text-indigo-700 border-indigo-300'
          }`"
        >
          {{
            questions[currentQuestion].type === "arithmetic"
              ? t("mathTest.categories.arithmetic")
              : questions[currentQuestion].type === "algebra"
              ? t("mathTest.categories.algebra")
              : questions[currentQuestion].type === "geometry"
              ? t("mathTest.categories.geometry")
              : questions[currentQuestion].type === "percentage"
              ? t("mathTest.categories.percentage")
              : questions[currentQuestion].type === "fraction"
              ? t("mathTest.categories.fraction")
              : t("mathTest.categories.wordProblem")
          }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <!-- Icon placeholder -->
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="lucide lucide-trophy w-4 h-4"
          >
            <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6c2.66 0 4 2 4 5V20h4v-7" />
            <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18c-2.66 0-4 2-4 5V20h4v-7" />
            <path d="M4 20v2" />
            <path d="M20 20v2" />
            <path d="M14 12v8" />
          </svg>
          <span class="font-semibold">{{ score }}</span>
        </div>
      </div>

      <div class="flex items-center gap-4">
        <div class="text-center">
          <div
            :class="`text-2xl font-bold font-mono ${
              questionTimeLeft <= 10 ? 'text-red-500' : 'text-blue-600'
            }`"
          >
            {{ questionTimeLeft }}
          </div>
          <div class="text-xs text-slate-500">
            {{ t("mathTest.time.questionTime") }}
          </div>
        </div>
        <div class="text-center">
          <div class="text-lg font-mono text-slate-600">
            {{ Math.floor(timeLeft / 60) }}:{{
              (timeLeft % 60).toString().padStart(2, "0")
            }}
          </div>
          <div class="text-xs text-slate-500">
            {{ t("mathTest.time.totalRemaining") }}
          </div>
        </div>
      </div>
    </div>

    <Progress
      :model-value="(currentQuestion / questions.length) * 100"
      class="h-2"
    />

    <Card class="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
      <CardHeader>
        <CardTitle class="text-xl text-slate-800">{{
          questions[currentQuestion].question
        }}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        <div className="flex gap-3">
          <Input
            type="number"
            step="any"
            v-model="userAnswer"
            :placeholder="t('mathTest.inputPlaceholder')"
            className="text-lg font-mono text-center"
            :disabled="showFeedback"
            @keypress="submitKeyPress"
          />
          <Button
            @click="handleSubmit"
            :disabled="!userAnswer || showFeedback"
            class="bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white px-8"
          >
            {{ t("mathTest.submitButton") }}
          </Button>
        </div>
      </CardContent>
    </Card>

    <!-- 反馈弹窗 -->
    <div
      v-if="showFeedback"
      class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-md"
    >
      <Card
        :class="`border-0 shadow-lg ${
          feedbackCorrect ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
        }`"
      >
        <CardContent class="py-4 px-6">
          <div class="text-center">
            <div class="font-semibold mb-2">
              {{
                feedbackCorrect
                  ? t("mathTest.feedback.correct")
                  : t("mathTest.feedback.incorrect")
              }}
            </div>
            <div v-if="!feedbackCorrect" class="text-sm opacity-90">
              {{ t("mathTest.feedback.correctAnswerPrefix")
              }}{{ feedbackAnswer }}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-blue-200 shadow-xl">
      <CardHeader class="text-center pb-6">
        <div
          class="w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <!-- Icon placeholder -->
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            class="lucide lucide-trophy w-10 h-10 text-white"
          >
            <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6c2.66 0 4 2 4 5V20h4v-7" />
            <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18c-2.66 0-4 2-4 5V20h4v-7" />
            <path d="M4 20v2" />
            <path d="M20 20v2" />
            <path d="M14 12v8" />
          </svg>
        </div>

        <CardTitle class="text-3xl text-slate-800 mb-2">{{
          t("mathTest.results.title")
        }}</CardTitle>
        <div
          class="text-6xl font-bold bg-gradient-to-r from-blue-600 to-cyan-500 bg-clip-text text-transparent"
        >
          {{ Math.round((score / questions.length) * 100) }}
        </div>
        <p class="text-slate-600">{{ t("mathTest.results.accuracyLabel") }}</p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200"
          >
            <div class="text-2xl font-bold text-blue-600 mb-1">
              {{ score }}/{{ questions.length }}
            </div>
            <div class="text-sm text-blue-700">
              {{ t("mathTest.results.correctCountLabel") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200"
          >
            <div class="text-2xl font-bold text-cyan-600 mb-1">
              {{
                Math.round(
                  responses.reduce((sum, r) => sum + r.time, 0) /
                    responses.length /
                    1000
                )
              }}s
            </div>
            <div class="text-sm text-cyan-700">
              {{ t("mathTest.results.averageTimeLabel") }}
            </div>
          </div>
        </div>

        <Button
          @click="handleComplete"
          class="w-full bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
        >
          {{ t("mathTest.results.viewDetailsButton") }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";

// State variables
const stage = ref("instructions"); // 'instructions' | 'test' | 'results'
const currentQuestion = ref(0);
const questions = ref([]);
const userAnswer = ref("");
const responses = ref([]);
const timeLeft = ref(600); // 10分钟总时间
const questionTimeLeft = ref(0);
const startTime = ref(0);
const questionStartTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);
const feedbackAnswer = ref(0);

const TOTAL_QUESTIONS = 20;
const emit = defineEmits(["complete"]);
const { t } = useI18n();
const submitKeyPress = (e) => {
  if (e.key === "Enter" && userAnswer.value.trim() && !showFeedback.value) {
    handleSubmit();
  }
};

// 动态生成数学题目
const generateQuestions = () => {
  const generatedQuestions = [];
  let questionId = 1;

  // 基础算术题 (6道)
  for (let i = 0; i < 6; i++) {
    generatedQuestions.push(generateArithmeticQuestion(questionId++));
  }

  // 代数题 (4道)
  for (let i = 0; i < 4; i++) {
    generatedQuestions.push(generateAlgebraQuestion(questionId++));
  }

  // 几何题 (3道)
  for (let i = 0; i < 3; i++) {
    generatedQuestions.push(generateGeometryQuestion(questionId++));
  }

  // 百分比题 (3道)
  for (let i = 0; i < 3; i++) {
    generatedQuestions.push(generatePercentageQuestion(questionId++));
  }

  // 分数题 (2道)
  for (let i = 0; i < 2; i++) {
    generatedQuestions.push(generateFractionQuestion(questionId++));
  }

  // 应用题 (2道)
  for (let i = 0; i < 2; i++) {
    generatedQuestions.push(generateWordProblem(questionId++));
  }

  // 随机打乱顺序
  return generatedQuestions.sort(() => Math.random() - 0.5);
};

const generateArithmeticQuestion = (id) => {
  const operations = ["+", "-", "×", "÷"];
  const operation = operations[Math.floor(Math.random() * operations.length)];

  let a, b, answer, question;

  switch (operation) {
    case "+":
      a = Math.floor(Math.random() * 500) + 10;
      b = Math.floor(Math.random() * 500) + 10;
      answer = a + b;
      question = `${a} + ${b} = ?`;
      break;
    case "-":
      a = Math.floor(Math.random() * 500) + 100;
      b = Math.floor(Math.random() * (a - 10)) + 10;
      answer = a - b;
      question = `${a} - ${b} = ?`;
      break;
    case "×":
      a = Math.floor(Math.random() * 25) + 5;
      b = Math.floor(Math.random() * 25) + 5;
      answer = a * b;
      question = `${a} × ${b} = ?`;
      break;
    case "÷":
      answer = Math.floor(Math.random() * 50) + 5;
      b = Math.floor(Math.random() * 20) + 2;
      a = answer * b;
      question = `${a} ÷ ${b} = ?`;
      break;
    default:
      a = 10;
      b = 5;
      answer = 15;
      question = "10 + 5 = ?";
  }

  return {
    id,
    type: "arithmetic",
    question,
    answer,
    difficulty: answer > 500 ? "hard" : answer > 100 ? "medium" : "easy",
    timeLimit: 30,
  };
};

const generateAlgebraQuestion = (id) => {
  const types = [
    "linear_equation",
    "quadratic_simple",
    "substitution",
    "factoring",
  ];

  const type = types[Math.floor(Math.random() * types.length)];

  switch (type) {
    case "linear_equation":
      const x = Math.floor(Math.random() * 20) + 1;
      const a = Math.floor(Math.random() * 10) + 2;
      const b = Math.floor(Math.random() * 50) + 10;
      const result = a * x + b;
      return {
        id,
        type: "algebra",
        question: `如果 ${a}x + ${b} = ${result}，那么 x = ?`,
        answer: x,
        difficulty: a > 5 ? "medium" : "easy",
        timeLimit: 45,
      };

    case "quadratic_simple":
      const root = Math.floor(Math.random() * 10) + 1;
      const constant = root * root;
      return {
        id,
        type: "algebra",
        question: `x² = ${constant}，那么正数解 x = ?`,
        answer: root,
        difficulty: "medium",
        timeLimit: 45,
      };

    case "substitution":
      const val = Math.floor(Math.random() * 10) + 1;
      const coeff = Math.floor(Math.random() * 5) + 2;
      const add = Math.floor(Math.random() * 20) + 5;
      const ans = coeff * val + add;
      return {
        id,
        type: "algebra",
        question: `如果 y = ${coeff}x + ${add}，当 x = ${val} 时，y = ?`,
        answer: ans,
        difficulty: "easy",
        timeLimit: 30,
      };

    default:
      return {
        id,
        type: "algebra",
        question: "2x + 3 = 11，那么 x = ?",
        answer: 4,
        difficulty: "easy",
        timeLimit: 30,
      };
  }
};

const generateGeometryQuestion = (id) => {
  const types = ["rectangle_area", "circle_area", "triangle_area", "perimeter"];
  const type = types[Math.floor(Math.random() * types.length)];

  switch (type) {
    case "rectangle_area":
      const length = Math.floor(Math.random() * 15) + 5;
      const width = Math.floor(Math.random() * 15) + 5;
      return {
        id,
        type: "geometry",
        question: `一个长方形的长为 ${length} 厘米，宽为 ${width} 厘米，面积是多少平方厘米？`,
        answer: length * width,
        difficulty: "easy",
        timeLimit: 35,
      };

    case "circle_area":
      const radius = Math.floor(Math.random() * 10) + 3;
      const area = Math.round(Math.PI * radius * radius);
      return {
        id,
        type: "geometry",
        question: `一个圆的半径为 ${radius} 厘米，面积约为多少平方厘米？（π ≈ 3.14）`,
        answer: area,
        difficulty: "medium",
        timeLimit: 45,
      };

    case "triangle_area":
      const base = Math.floor(Math.random() * 20) + 6;
      const height = Math.floor(Math.random() * 15) + 4;
      return {
        id,
        type: "geometry",
        question: `一个三角形的底为 ${base} 厘米，高为 ${height} 厘米，面积是多少平方厘米？`,
        answer: (base * height) / 2,
        difficulty: "easy",
        timeLimit: 40,
      };

    default:
      const side = Math.floor(Math.random() * 15) + 5;
      return {
        id,
        type: "geometry",
        question: `一个正方形的边长为 ${side} 厘米，周长是多少厘米？`,
        answer: side * 4,
        difficulty: "easy",
        timeLimit: 25,
      };
  }
};

const generatePercentageQuestion = (id) => {
  const types = ["percentage_of", "percentage_increase", "discount"];
  const type = types[Math.floor(Math.random() * types.length)];

  switch (type) {
    case "percentage_of":
      const total = Math.floor(Math.random() * 500) + 100;
      const percentage = [10, 20, 25, 30, 40, 50, 75][
        Math.floor(Math.random() * 7)
      ];
      const result = (total * percentage) / 100;
      return {
        id,
        type: "percentage",
        question: `${total} 的 ${percentage}% 是多少？`,
        answer: result,
        difficulty: percentage > 50 ? "medium" : "easy",
        timeLimit: 35,
      };

    case "percentage_increase":
      const original = Math.floor(Math.random() * 200) + 50;
      const increase = [10, 15, 20, 25, 30][Math.floor(Math.random() * 5)];
      const increased = original * (1 + increase / 100);
      return {
        id,
        type: "percentage",
        question: `一个数是 ${original}，增加 ${increase}% 后是多少？`,
        answer: increased,
        difficulty: "medium",
        timeLimit: 40,
      };

    default:
      const price = Math.floor(Math.random() * 300) + 100;
      const discount = [10, 15, 20, 25, 30][Math.floor(Math.random() * 5)];
      const finalPrice = price * (1 - discount / 100);
      return {
        id,
        type: "percentage",
        question: `原价 ${price} 元的商品打 ${
          100 - discount
        } 折，现价是多少元？`,
        answer: finalPrice,
        difficulty: "medium",
        timeLimit: 40,
      };
  }
};

const generateFractionQuestion = (id) => {
  const types = ["fraction_add", "fraction_multiply"];
  const type = types[Math.floor(Math.random() * types.length)];

  if (type === "fraction_add") {
    // 同分母分数加法
    const denominator = [4, 6, 8, 10, 12][Math.floor(Math.random() * 5)];
    const num1 = Math.floor(Math.random() * (denominator - 1)) + 1;
    const num2 = Math.floor(Math.random() * (denominator - num1)) + 1;
    const sum = num1 + num2;

    return {
      id,
      type: "fraction",
      question: `${num1}/${denominator} + ${num2}/${denominator} = ? （用最简分数表示，如果是整数就填整数）`,
      answer: sum === denominator ? 1 : sum,
      difficulty: "easy",
      timeLimit: 45,
    };
  } else {
    // 分数乘整数
    const numerator = Math.floor(Math.random() * 5) + 1;
    const denominator = [4, 6, 8][Math.floor(Math.random() * 3)];
    const multiplier = Math.floor(Math.random() * 4) + 2;
    const result = (numerator * multiplier) / denominator;

    return {
      id,
      type: "fraction",
      question: `${numerator}/${denominator} × ${multiplier} = ? （小数形式）`,
      answer: Math.round(result * 100) / 100,
      difficulty: "medium",
      timeLimit: 50,
    };
  }
};

const generateWordProblem = (id) => {
  const problems = [
    {
      question:
        "小明买了3支笔，每支12元，又买了2本书，每本25元。他总共花了多少钱？",
      answer: 3 * 12 + 2 * 25,
    },
    {
      question: "一辆车每小时行驶80公里，行驶了3.5小时，总共行驶了多少公里？",
      answer: 80 * 3.5,
    },
    {
      question: "学校有480名学生，其中3/8是女生，女生有多少人？",
      answer: (480 * 3) / 8,
    },
    {
      question: "一个长方形的周长是36米，长是12米，宽是多少米？",
      answer: (36 - 12 * 2) / 2,
    },
    {
      question: "商店原价100元的商品打8折销售，顾客实际支付多少元？",
      answer: 100 * 0.8,
    },
  ];

  const selectedProblem = problems[Math.floor(Math.random() * problems.length)];

  return {
    id,
    type: "word_problem",
    question: selectedProblem.question,
    answer: selectedProblem.answer,
    difficulty: "medium",
    timeLimit: 60,
  };
};

let intervalId = null;

watch(
  [stage, timeLeft, showFeedback],
  ([newStage, newTimeLeft, newShowFeedback]) => {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
    if (newStage === "test" && newTimeLeft > 0) {
      intervalId = setInterval(() => {
        timeLeft.value--;

        if (timeLeft.value <= 1) {
          stage.value = "results";
          timeLeft.value = 0;
        }

        questionTimeLeft.value--;
        if (questionTimeLeft.value <= 1 && !newShowFeedback) {
          // 时间到，自动提交空答案
          handleSubmit();
        }
      }, 1000);
    }
  }
);

watch([currentQuestion, stage], ([newCurrentQuestion, newStage]) => {
  if (newStage === "test" && questions.value.length > 0) {
    questionTimeLeft.value = questions.value[newCurrentQuestion].timeLimit;
    questionStartTime.value = Date.now();
  }
});

const handleStartTest = () => {
  const generatedQuestions = generateQuestions();
  questions.value = generatedQuestions;
  stage.value = "test";
  startTime.value = Date.now();
  questionStartTime.value = Date.now();
  questionTimeLeft.value = generatedQuestions[0]?.timeLimit || 30;
};

const handleSubmit = () => {
  console.log("handleSubmit called");
  console.log("userAnswer:", userAnswer.value);
  console.log("currentQuestion:", currentQuestion.value);
  console.log("questions:", questions.value);

  const question = questions.value[currentQuestion.value];
  if (!question) {
    console.error(
      "Question not found!",
      currentQuestion.value,
      questions.value
    );
    return;
  }
  const userNum = parseFloat(userAnswer.value) || 0;
  const correct = Math.abs(userNum - question.answer) < 0.01; // 允许小数误差
  const reactionTime = Date.now() - questionStartTime.value;

  responses.value = [
    ...responses.value,
    {
      answer: userNum,
      correct,
      time: reactionTime,
    },
  ];

  if (correct) {
    score.value++;
  }

  // 显示反馈
  feedbackCorrect.value = correct;
  feedbackAnswer.value = question.answer;
  showFeedback.value = true;
  console.log("showFeedback set to true", showFeedback.value);

  setTimeout(() => {
    showFeedback.value = false;
    userAnswer.value = "";
    console.log("showFeedback set to false", showFeedback.value);

    if (currentQuestion.value < questions.value.length - 1) {
      currentQuestion.value++;
      console.log("Next question:", currentQuestion.value);
    } else {
      stage.value = "results";
      console.log("Stage set to results");
    }
  }, 1500);
};

const handleComplete = () => {
  const totalQuestions = questions.value.length;
  const correctAnswers = score.value;
  const accuracy = Math.round((correctAnswers / totalQuestions) * 100);
  const averageTime = Math.round(
    responses.value.reduce((sum, r) => sum + r.time, 0) / responses.value.length
  );
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  // 按题目类型分类统计
  const typeStats = {};

  questions.value.forEach((question, index) => {
    const type = question.type;
    if (!typeStats[type]) {
      typeStats[type] = { correct: 0, total: 0 };
    }
    typeStats[type].total++;
    if (responses.value[index]?.correct) {
      typeStats[type].correct++;
    }
  });

  const result = {
    id: Date.now().toString(),
    testType: "math",
    score: accuracy,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalQuestions,
      correctAnswers,
      accuracy,
      averageTimePerQuestion: averageTime,
      typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
        type:
          type === "arithmetic"
            ? "基础运算"
            : type === "algebra"
            ? "代数"
            : type === "geometry"
            ? "几何"
            : type === "percentage"
            ? "百分比"
            : type === "fraction"
            ? "分数"
            : "应用题",
        accuracy:
          stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
        correct: stats.correct,
        total: stats.total,
      })),
      questionsGenerated: questions.value.map((q) => ({
        type: q.type,
        difficulty: q.difficulty,
      })),
    },
  };
  emit("complete", result);
  // Assuming onComplete is passed as a prop or provided via inject
  // For now, we'll just log it or handle it internally
  console.log("Test Complete:", result);
};

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>
